/*
 * Copyright (c) 2020 Fraunhofer FOKUS and others. All rights reserved.
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contact: mosaic@fokus.fraunhofer.de
 */

package org.eclipse.mosaic.fed.mqtt.message;

import org.eclipse.mosaic.fed.mqtt.protocol.AbstractProtocol;
import org.eclipse.mosaic.lib.util.JsonUtils;

import java.lang.reflect.Method;

/**
 * Mqtt Message
 */
public abstract class AbstractMqttMessage<T extends AbstractProtocol> {

    private final T payload;

    private final Class<T> protocol;

    private final String message;

    public AbstractMqttMessage(String message, Class<T> protocol) {
        this.message = message;
        this.protocol = protocol;
        try {
            // deserialize by Json
            payload = JsonUtils.deserialize(message, protocol);
        } catch (Exception e) {
            throw new RuntimeException("message cannot transfer to " + protocol.getName() + " .");
        }
    }

    public String getMessage() {
        return message;
    }

    public T getPayload() {
        return payload;
    }

    public Class<T> getProtocol() {
        return protocol;
    }

    public String getId() {
        Method method = null;
        try {
            method = protocol.getMethod("getId");
            return (String) method.invoke(payload);
        } catch (Exception e) {
            throw new RuntimeException("Getting id from message error.", e);
        }

    }

    public long getTimestamp() {
        Method method = null;
        try {
            method = protocol.getMethod("getTimestamp");
            return (long) method.invoke(payload);
        } catch (Exception e) {
            throw new RuntimeException("Getting timestamp from message error.", e);
        }

    }
}
